<template>
    <div class="chapterExercise">
        <Header></Header>
        <div class="main">
            <div class="banner">
                <img style="width: 100%" src="https://img.js.design/assets/img/617766b867e5da8dd2a409b5.png" alt="">
            </div>
            <div class="breadcrumb">
                <el-breadcrumb :separator-icon="'ArrowRightBold'">
                    <el-breadcrumb-item class="link" @click="toIndex">首页</el-breadcrumb-item>
                    <el-breadcrumb-item class="link" @click="toQuestionBack">我的题库</el-breadcrumb-item>
                    <el-breadcrumb-item class="link" @click="toBack">{{subject_name}}</el-breadcrumb-item>
                    <el-breadcrumb-item>练习题详情</el-breadcrumb-item>
                </el-breadcrumb>
            </div>
            <div style="align-items: center" v-if="subjects">
                <el-row :gutter="20" style="margin-right: 0">
                    <el-col :span="17">
                        <el-card class="box-card">
                            <template #header>
                                <el-row>
                                    <el-col :span="6" style="display: flex;align-items: center">
                                        <span v-if="active_subject.parent_id">
                                            第{{active_subject.parent_sort}}-{{active_subject.sort}}题，{{active_subject.type_name}}
                                        </span>
                                        <span v-else>
                                            第{{active_subject.sort}}题，{{active_subject.type_name}}
                                        </span>
<!--                                        <span>{{`第${active_idx+1}题，${active_subject.type_name}`}}</span>-->
                                    </el-col>
                                    <el-col :span="18">
                                        <div class="card-header">
                                            <div>
                                                <el-button-group>
<!--                                                    <el-button :type="active_subject.flag?'primary':''"-->
<!--                                                               size="small"-->
<!--                                                               @click="active_subject.flag=!active_subject.flag">-->
<!--                                                        <el-icon>-->
<!--                                                            <Flag/>-->
<!--                                                        </el-icon>-->
<!--                                                        &nbsp;{{active_subject.flag?' 取消':'标记'}}-->
<!--                                                    </el-button>-->
<!--                                                    <el-button @click="addLike(active_subject.topic_id)" size="small" :type="active_subject.is_collect?'primary':''">-->
<!--                                                        <el-icon><StarFilled /></el-icon>收藏-->
<!--                                                    </el-button>-->
                                                    <el-button size="small" @click="checked"><el-icon><View /></el-icon>&nbsp;解析</el-button>
                                                </el-button-group>
                                            </div>
                                        </div>
                                    </el-col>
                                </el-row>

                            </template>
                          <el-button style="margin-right: 15px;margin-bottom: 15px" size="small" v-if="activeMaxTopic" type="primary" @click="isCase = !isCase">查看题目背景</el-button>
                            <Question
                                    :subject="active_subject"
                                    v-model:user_answer="active_subject.user_answer"
                                    :mode="mode"
                                    @checked="checked">
                            </Question>
                            <div v-show="analysisIsShow">
                                <el-alert
                                          description="description" show-icon
                                          :closable="false">
                                    <div slot="title">
                                        您的答案: {{active_subject.answer}}
                                    </div>
                                </el-alert>
                                <el-alert v-if="active_subject.desc" type="info" description="description" show-icon :closable="false">
                                    <div slot="default" v-html="active_subject.desc" style="margin-top: 5px">
                                    </div>
                                </el-alert>
                            </div>
                        </el-card>
<!--                        <div style="margin-top: 30px">-->
<!--                            <el-button-group>-->
<!--                                <el-button type="primary" @click="pre" :disabled="active_idx<=0">-->
<!--                                    {{'< 上一题'}}-->
<!--                                </el-button>-->
<!--                                <el-button type="primary" @click="next" :disabled="active_idx>=subjects.length-1">-->
<!--                                    {{'下一题 >'}}-->
<!--                                </el-button>-->
<!--                            </el-button-group>-->
<!--                        </div>-->
<!--                        <div v-html="leads[active_subject.parent_id]"></div>-->
                    </el-col>
                    <el-col :span="7">
                        <div class="grid-content bg-purple-dark"/>
                        <div class="button-group">
                            <div style="display: flex">
                                <el-button size="small" plain type="primary" :icon="'Tickets'" style="margin-right: 16px" @click="tableOfRates = !tableOfRates">税率表</el-button>
                                <el-button size="small" plain type="primary" :icon="'Search'" @click="showCalculator">计算器</el-button>
                            </div>
                        </div>
                    </el-col>
                </el-row>
            </div>
            <el-empty v-else style="height:560px;" :image-size="200" description="暂无数据" />
        </div>
      <TableOfRates v-model="tableOfRates" :img-url="imgUrl"></TableOfRates>
      <Case v-show="isCase" @anliClose="anliClose" :isShowCase="active_subject && active_subject.parent_id ? true:false" :caseContent="caseContent"></Case>
        <div class="parent" v-if="isCalculator">
            <Vue3DraggableResizable
                    :initW="280"
                    :minW="220"
                    v-model:x="x"
                    v-model:y="y"
                    v-model:w="w"
                    v-model:h="h"
                    v-model:active="active"
                    :draggable="true"
                    :resizable="true"
                    @activated="print('activated')"
                    @deactivated="print('deactivated')"
                    @drag-start="print('drag-start')"
                    @resize-start="print('resize-start')"
                    @dragging="print('dragging')"
                    @resizing="print('resizing')"
                    @drag-end="print('drag-end')"
                    @resize-end="print('resize-end')"
            >
              <Calculator @closeCalcuator="closeCalcuator"></Calculator>
            </Vue3DraggableResizable>
        </div>
        <staticFooter></staticFooter>
    </div>
</template>

<script>
import TableOfRates from "@/components/TableOfRates";
    import Case from "../../../components/Case";
    import staticFooter from "../../../components/staticFooter";
    import Calculator from "../../../components/calculator/Calculator";
    import {submit_result,submitAnswer} from "../../../hock/submit_question/submit_questions";
    import SubmitAnswerSheet from "../../../components/submitAnswerSheet/SubmitAnswerSheet";
    import goBackHistory from "../../../utils/hook/goBackHistory";
    import Question from "../../../components/Question/Question";
    import Picker from "../../../components/Picker/Picker";
    import comm_chapter from "../../../hock/composables/comm_chapter";

    import {Flag} from '@element-plus/icons-vue'
    import {ref, watch} from 'vue'
    import Header from "../../../components/Header";
    import {useRoute, useRouter} from "vue-router";
    import {reactive,toRefs,onBeforeUnmount,getCurrentInstance} from 'vue'
    import {collectTopic, taxRateTable} from "../../../api/api";
    import source_to_subjects from "../../../hock/public/source_to_subjects";
    import {ElMessage,ElMessageBox} from "element-plus";
    import {meCollect} from "../../../utils/hook/addLike/meCollect";
    export default {
        name: "index",
        setup() {
            let route = useRoute();
            let router = useRouter();
            const { proxy } = getCurrentInstance()
            let data = reactive({
                x: 100,
                y: 100,
                h: 100,
                w: 100,
                active: false,
                isCalculator:false,
                id:null,
                ques_list:[],
                mode:'train',
                subject_name:'',
                question_result:false,
                correctS:null,//答题正确率
                correctNum:null,//答题正确数
                answer:null, //已答题数
                activeMaxTopic:false,
                isCase:false,
                caseContent:null,//案例
                analysisIsShow:false,
                tableOfRates:false
            })
            data.id = route.params.id;
            data.subject_name = route.params.subject_name;
            const active_idx = ref(0)
            const active_subject = ref(null)
            const {source, subjects, leads,question_id} = comm_chapter('collectTopic',{id:Number(data.id)})
            let getCollectTopic = () =>{
                collectTopic({id:Number(data.id)}).then(res =>{
                    console.log('当前数据',res)
                    if(res.data.maxTopic){
                        data.activeMaxTopic = true;
                        data.caseContent = res.data.maxTopic.stem;
                    }
                }).catch(err =>{
                    ElMessage({type:'error',message:err.message})
                })
            }
            getCollectTopic();
            let setTimer = setInterval(() =>{
                try {
                    source.value.useTime = source.value.useTime ? source.value.useTime : 0;
                    source.value.useTime ++
                }catch (e) {

                }
            },1000)

          const closeCalcuator = (param) =>{
            data.isCalculator = param;
          }

            let anliClose = () =>{
                data.isCase = false
            }

            let lookAnalysis = () =>{
                data.analysisIsShow = !data.analysisIsShow
            }

            let sumbmitResult = (result) =>{
                console.log('result',result.res)
                let {correctS,correctNum,mistakeNum,unansweredNum} = result.res.data;
                data.correctS = correctS;
                data.correctNum = correctNum;
                data.answer = (correctNum+mistakeNum+unansweredNum) - unansweredNum;
                const subjects_leads = source_to_subjects(result.res.data);
                console.log('subjects_leads',subjects_leads)
                subjects.value = subjects_leads.subjects
                leads.value = subjects_leads.leads
                data.mode = 'analysis'
                data.question_result = true;
                clearInterval(setTimer)
            }
            let submitAnswerFun = async () =>{
                let answerSheet = {
                    state:1,
                    id:source.value.id,
                    index:active_idx.value,
                    useTime: source.value.useTime,
                    answerLogs:answerLogs()
                }
                let result = await submitAnswer(answerSheet,'chapterFinishUpOb');
                sumbmitResult(result)
            }
            let answerLogs = () => {
                let answerLogs = [];
                for (let item of subjects.value) {
                    if (item.user_answer) {
                        answerLogs.push({id: item.id, answer: item.user_answer.split('')});
                    }
                }
                return answerLogs;
            }
            watch(active_idx, () => {
                active_subject.value = subjects.value[active_idx.value]
            })
            watch(source, () => {
                active_subject.value = subjects.value[active_idx.value]
            })
            const checked = () => {
                active_subject.value.checked = true
            }
            const next = () => {
                active_idx.value = (active_idx.value + 1) % subjects.value.length
            }
            const pre = () => {
                active_idx.value -= 1
            }
            let closeSubmit = async () =>{
                let answerSheet = {
                    state:0,
                    id:source.value.id,
                    index:active_idx.value,
                    useTime: source.value.useTime,
                    answerLogs:answerLogs()
                }
                let result = await submitAnswer(answerSheet,'chapterFinishUpOb');
                console.log(result)
                clearInterval(setTimer)
            }
            let toIndex = () =>{
                router.push({name:'index'})
                let urlParams = goBackHistory.return_history();
                router.push({name:urlParams.name,params:urlParams.params})
            }
            let toQuestionBack = () =>{
                router.push({name:'MyQuestionBank'})
                let urlParams = goBackHistory.return_history();
                router.push({name:urlParams.name,params:urlParams.params})
            }

            let toBack = () =>{
                let urlParams = goBackHistory.return_history();
                router.push({name:urlParams.name,params:urlParams.params})
            }
            let showCalculator = () =>{
                data.isCalculator = !data.isCalculator
            }
            let print = (val) => {
                console.log(val)
            }
            //添加或取消收藏
            let addLike = (id) =>{
                active_subject.value.is_collect = !active_subject.value.is_collect;
                meCollect(id);
            }
            let imgUrl = ref('')
            let getTaxRateTable = () =>{
                taxRateTable().then(res =>{
                    console.log(res)
                    imgUrl.value = res.data[0]
                })
            }
            getTaxRateTable();
            return {
              closeCalcuator,
                imgUrl,
                lookAnalysis,
                anliClose,
                addLike,
                showCalculator,
                print,
                proxy,
                toIndex,
                toQuestionBack,
                submitAnswerFun,
                sumbmitResult,
                question_id,
                toBack,
                ...toRefs(data),
                active_idx,
                active_subject,
                source,
                subjects,
                checked,
                next,
                pre,
                leads,
            }
        },
        components:{
          TableOfRates,
            Header,
            Question,
            Picker,
            SubmitAnswerSheet,
            Calculator,
            staticFooter,
            Case
        }
    }
</script>

<style>
    .button-group .el-button{
        width: 48%;
    }
</style>

<style scoped>
    .parent {
        width: 200px;
        height: 200px;
        position: absolute;
        top: 0px;
        right: 200px;
        user-select: none;
    }
    .button-group{
        display: flex;
        justify-content: center;
        margin-bottom: 20px;
    }
    .button-group div{
        width: 100%;
    }
    .submit-button{
        width: 100%;
    }
    .percentage-value {
        display: block;
        font-size: 15px;
        color: #409eff;
    }
    .percentage-label {
        display: block;
        margin-top: 5px;
        font-size: 12px;
    }
    .demo-progress{
        padding: 10px;
        background-color: white;
        display: flex;
        justify-content: space-around;
        margin-bottom: 14px;
    }
    .question_result .card{
        background: rgba(42, 130, 228, 1);
        border-top-left-radius: 10px;
        border-top-right-radius: 10px;
        padding: 10px 0;
        text-align: center;
        color: white;
    }
    .chapterExercise{
        background-color: rgba(247, 247, 247, 1);
    }
    .card-header{
        display: flex;
        justify-content: flex-end;
        align-items: center;
    }
    .link{
        cursor: pointer;
    }
    .link:hover{
        color: skyblue;
    }
    .main{
        padding-top: 60px;
        margin: 0 auto;
        width: 75rem;
        margin-bottom: 240px;
    }
    .breadcrumb{
        height: 40px;
        display: flex;
        align-items: center;
    }
    .banner{
        width: 100%;
        height: 15rem;
        position: relative;
        overflow: hidden;
    }
    .banner > img {
        position: absolute;
        top: -100%;

    }
</style>
